package com.main.tripplanner.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.main.tripplanner.persistent.Attraction;
import com.main.tripplanner.persistent.AttractionQuestion;
import com.main.tripplanner.persistent.Country;

@Repository
public class AttractionQuestionDAO extends AbstractDAO{
	private static final int CONSTANT_BAR = 20;
	public AttractionQuestion getNextAttractionQuestion(Country country) {
		Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(AttractionQuestion.class);
		criteria.add(Restrictions.eq("country", country));
		List<AttractionQuestion> list = criteria.list();
		if(list.size() ==0){
			return null;
		}
		else{
			return minimalPotentialAttraction(list);
		}
	}


	public List<AttractionQuestion> getAttractionQuestionByBestReplacementAttraction(Attraction attraction) {
		Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(AttractionQuestion.class);
		criteria.add(Restrictions.eq("bestCandidateToReplace", attraction));
		return criteria.list();
	}

	private AttractionQuestion minimalPotentialAttraction(List<AttractionQuestion> list) {
		int potential = CONSTANT_BAR;
		AttractionQuestion attractionQuestionResult = null;
		for (AttractionQuestion attractionQuestion : list) {
			if(potential > attractionQuestion.getNumberOfQuestionsToReplace()){
				attractionQuestionResult = attractionQuestion;
				potential = attractionQuestion.getNumberOfQuestionsToReplace();
			}
		}
		return attractionQuestionResult;
	}


	public AttractionQuestion getAttractionQuestionById(int attractionQuestionId) {
		Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(AttractionQuestion.class);
		criteria.add(Restrictions.eq("id", attractionQuestionId));
		List<AttractionQuestion> list = criteria.list();
		return (list == null) ? null : list.get(0);
	}
}
